<?php

namespace app\api\controller;

use addons\shopro\model\UserWalletLog;
use app\common\controller\Api;
use app\common\model\RetailUser;
use think\Db;
use think\Exception;
use addons\shopro\model\Order;
use addons\shopro\model\OrderItem;
use addons\shopro\model\User;
use addons\shopro\model\Giftlog;
use app\common\model\RetailConfig;


/**
 * 分销相关接口
 */
class Retail extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 粉丝晋级接口
     *
     * @param string order_id 订单号
     * @param string user_id 用户ID
     */
    protected function upgrade($user_id)
    {
        //判断用户当前等级,如果不是粉丝则跳过
        $userModel = new User();
        $model = new RetailUser();
        $retailUser = $model->getUserInfo($user_id);
        if(empty($retailUser) || $retailUser['level'] != RetailUser::LEVEL_FENS){
            //不是粉丝不能晋级
            return 0;
        }

        //1.粉丝变成玩客
        $saveData = [
            'level' => RetailUser::LEVEL_WANKE,
            'level_time' => time(),
        ];
        $retailUser = array_merge($saveData,$retailUser);
        db('retail_user')->where(['uid'=>$retailUser['uid']])->update($saveData);

        //2.奖金池
        RetailUser::insReward($retailUser);

        //3. 分配给直属上级X元,retail_config.recommend字段,根据B的等级来决定给多少推荐奖励
        $parent = $model->getUserInfo($retailUser['pid']);

        //奖励配置
        $retailConfigModel = new RetailConfig();
        $conf   = $retailConfigModel->getRecommendConfig();

        /*--------粉丝升级玩客的时候给予上级奖励--------*/

        $give_money = $conf[$parent['level']];
        Db::startTrans();
        try{
            $user = clone $userModel;
            $useradd = $user->find($parent['uid']);
            //钱包余额
            db('user')->where(['id'=>$useradd->id])->setInc('money',$give_money);
            //计算累计收益
            db('retail_user')->where(['uid'=>$useradd->id])->setInc('total_income',$give_money);

            $model = new UserWalletLog();
            $model->doAdd($useradd, $give_money, "recommend", $retailUser['uid'], "money", 1);

            Db::commit();
        }catch (\Exception $e){
            \think\Log::error("直属晋级赠送报错:".$e->getMessage());
            DB::rollback();
        }

        /***************循环判断所有上级是否满足晋级条件**************/
        $child         = $retailUser;
        $is_zhishu     = true;//是否是直属下级晋级
        $acc_up_wanke  = 1;//累计晋级玩客
        $acc_up_wanzhu = 0;//累计晋级玩主
        $acc_up_wanjia = 0;//累计晋级玩家

        $count = 1000;//最多有1000级
        while( !empty($parent) && $count !=0 ){
            $count--;
            $updata = [];//更新的数据

            //判断下级的等级来决定上级直属下级的数量
            switch($child['level']){
                case RetailUser::LEVEL_WANKE:
                    $zhishu_num = $is_zhishu ? 1:0;
                    $updata['wanke_num']    = $parent['wanke_num'] + $zhishu_num;
                    break;
                case RetailUser::LEVEL_WANZHU:
                    $zhishu_num = $is_zhishu ? 1:0;
                    $updata['wanzhu_num'] = $parent['wanzhu_num'] + $zhishu_num;
                    break;
                case RetailUser::LEVEL_WANJIA:
                    $zhishu_num = $is_zhishu ? 1:0;
                    $updata['wanjia_num'] = $parent['wanjia_num'] + $zhishu_num;
                    break;
            }

            //累计
            $updata['wanke_total']   = $parent['wanke_total'] + $acc_up_wanke;
            $updata['wanzhu_total']  = $parent['wanzhu_total'] + $acc_up_wanzhu;
            $updata['wanjia_total']  = $parent['wanjia_total'] + $acc_up_wanjia;

            //判断晋级条件
            switch($parent['level']){
                case RetailUser::LEVEL_WANKE:
                    if($updata['wanke_num'] >= RetailUser::UP_WANKE && $updata['wanke_total'] >= RetailUser::UP_WANKE_TOTAL){
                        //可以晋升,满足晋升条件
                        $updata['level'] = RetailUser::LEVEL_WANZHU;
                        $updata['level_time'] = time();

                        $acc_up_wanzhu++;
                        $is_zhishu = true;
                    }else{
                        //下一个上级就不是直属了;
                        $is_zhishu = false;
                    }
                    break;
                case RetailUser::LEVEL_WANZHU:
                    if($updata['wanke_num'] >= RetailUser::UP_WANZHU
                        && $updata['wanke_total'] >= RetailUser::UP_WANZHU_TOTAL
                        && $updata['wanzhu_num'] >= RetailUser::UP_WANZHU_ZHISHU){
                        //可以晋升,满足晋升条件
                        $updata['level'] = RetailUser::LEVEL_WANJIA;
                        $updata['level_time'] = time();

                        $acc_up_wanjia++;
                        $is_zhishu = true;
                    }else{
                        //下一个上级就不是直属了;
                        $is_zhishu = false;
                    }
                    break;
                case RetailUser::LEVEL_WANJIA:
                    $is_zhishu = false;
                    break;
                default:
                    $is_zhishu = false;
                    break;
            }

            //更新上级数据
            $parent = array_merge($updata,$parent);
            db('retail_user')->where(['uid'=>$parent['uid']])->update($updata);

            //继续获取下一个上级信息
            $child  = $parent;
            $parent = db('retail_user')->where(['uid'=>$parent['pid']])->find();
        }

        return 1;
    }

    /**
     * 普通会员变成粉丝的接口(扫码绑定)
     * @param string user_pid 用户绑定的上级ID
     * @param string user_id 当前用户ID
     */
    public function uptofens()
    {
        if(!request()->post()){
            $this->error('非法请求');
        }

        $user_pid   = $this->request->request("user_pid");
        $user_id    = $this->request->request("user_id");

        if (empty($user_pid) || empty($user_id)) {
            $this->error('非法参数');
        }

        //判断上级user_pid是否是玩客或以上,不是则忽略
        $parent = db('retail_user')->find($user_pid);
        if(empty($parent) || $parent['level'] < 2){
            $this->error('非法上级会员');
        }

        //判断user_id是否是普通用户,如果已经是会员了,即粉丝以上,则忽略
        $retail_user = db('retail_user')->find($user_id);
        if(!empty($retail_user)){
            $this->error('此用户已经绑定过上级会员了');
        }

        $user = db('user')->find($user_id);
        if(empty($user)){
            $this->error('非法用户');
        }

        /*******************开始成为粉丝*************/
        Db::startTrans();
        try{
            $retail_user_data = [
                'uid' => $user_id,
                'level' => RetailUser::LEVEL_FENS,
                'level_time'=> time(),
                'pid'   => $user_pid,
                'create_time'=> time(),
            ];
            //retail_user添加一条数据
            db('retail_user')->insert($retail_user_data);

            //更新上级的直属粉丝数量和累计粉丝数量
            $updata = [
                'fens_num' => $parent['fens_num'] + 1,
            ];

            db('retail_user')->where(['uid'=>$parent['uid']])->update($updata);

            Db::commit();

        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("绑定成功");
    }

    public function test()
    {
        $this->upgrade(4);exit;
        db('user')->where(['id'=>1])->setInc('money',100);
        exit;
        $user = model('user')->find(1);
        $wallet = 100;
        $is_add = 1;
        $type = "recommend";
        $item_id = 1;
        $wallet_type = "money";

        $model = new UserWalletLog();
        $ret = $model->doAdd($user, $wallet, $type, $item_id, $wallet_type, $is_add);

        //$conf = model('retail_config')->getRecommendConfig();
        halt($ret);
    }

    /**
     * 改变上级
     */
    public function changeParent()
    {
        //
        $child_user_id = 7;//需要修改的下级会员ID
        $new_parent_id = 6;//更换之后的上级会员ID

        //会员是否存在上级
        $retailUser = model('retail_user')->getUserInfo($child_user_id);
        if(empty($retailUser) ){
            return '非会员';
        }elseif($retailUser['level'] == RetailUser::LEVEL_WANZHU){
            return "玩主不能更换上级";
        }elseif($retailUser['level'] == RetailUser::LEVEL_WANJIA){
            return "玩家不能更换上级";
        }elseif($retailUser['wanzhu_total'] > 0){
            return "此会员已经有育成玩主,不能更换";
        }elseif($retailUser['wanjia_total'] > 0){
            return "此会员已经有育成玩家,不能更换";
        }elseif($retailUser['level'] == RetailUser::LEVEL_FENS && $retailUser['wanke_total'] > 0 ){
            return "此会员是粉丝已经有育成玩客了,不能更换";
        }

        $newParentUser = model('retail_user')->getUserInfo($new_parent_id);
        if(empty($newParentUser)){
            return "新上级非会员,无效";
        }


        /***************重新计算原来上级的团队人数,减掉相应的数量,循环所有旧上级 BEGIN**************/
        $oldParentUser = model('retail_user')->getUserInfo($retailUser['pid']);

        //判断下级的等级来决定上级直属下级的数量
        switch($retailUser['level']){
            case RetailUser::LEVEL_FENS:
                $updata['fens_num'] = $oldParentUser['fens_num'] - 1;
                $acc_up_wanke  = $retailUser['wanke_total'];//累计玩客
                $acc_up_fens   = $retailUser['fens_total'] + 1;//累计粉丝
                break;
            case RetailUser::LEVEL_WANKE:
                $updata['wanke_num']= $oldParentUser['wanke_num'] - 1;
                $acc_up_wanke  = $retailUser['wanke_total'] + 1;//累计玩客
                $acc_up_fens   = $retailUser['fens_total'];//累计粉丝
                break;
            default:
                return '会员等级错误';
                break;
        }

        while( !empty($oldParentUser)){
            $updata['wanke_total']  = $oldParentUser['wanke_total'] - $acc_up_wanke;
            $updata['fens_total']   = $oldParentUser['fens_total'] - $acc_up_fens;

            //更新上级数据
            db('retail_user')->where(['uid'=>$oldParentUser['uid']])->update($updata);

            //继续获取下一个上级信息
            $updata = [];//更新的数据
            $oldParentUser = db('retail_user')->where(['uid'=>$oldParentUser['pid']])->find();
        }
        /***************重新计算原来上级的团队人数,减掉相应的数量,循环所有旧上级 END**************/

        ////////////////更新变更会员的上级ID
        db('retail_user')->where(['uid'=>$retailUser['uid']])->update(['pid'=>$newParentUser['uid']]);

        /***************循环判断所有上级是否满足晋级条件 BEGIN**************/
        switch($retailUser['level']){
            case RetailUser::LEVEL_FENS:
                $updata['fens_num'] = $newParentUser['fens_num'] + 1;
                $acc_up_wanke  = $retailUser['wanke_total'];//累计玩客
                $acc_up_fens   = $retailUser['fens_total'] + 1;//累计粉丝
                break;
            case RetailUser::LEVEL_WANKE:
                $updata['wanke_num']= $newParentUser['wanke_num'] + 1;
                $acc_up_wanke  = $retailUser['wanke_total'] + 1;//累计玩客
                $acc_up_fens   = $retailUser['fens_total'];//累计粉丝
                break;
            default:
                return '会员等级错误';
                break;
        }

        while( !empty($newParentUser)){
            $updata['wanke_total']  = $newParentUser['wanke_total'] + $acc_up_wanke;
            $updata['fens_total']   = $newParentUser['fens_total'] + $acc_up_fens;

            //更新上级数据
            db('retail_user')->where(['uid'=>$newParentUser['uid']])->update($updata);

            //继续获取下一个上级信息
            $updata = [];//更新的数据
            $newParentUser = db('retail_user')->where(['uid'=>$newParentUser['pid']])->find();
        }
        /***************循环判断所有上级是否满足晋级条件 END**************/

    }

    public function test2(){
        $parent['uid'] = 1;
        $data = $this->digui($parent);

    }

    public function digui($parent){
        //无下级的用户
        $child = db('retail_user')->where(['pid'=>$parent['uid']])->select();
        $data = [
            'fens_num' =>0,
            'wanke_num' =>0,
            'wanzhu_num'=>0,
            'wanjia_num' =>0,
            'fens_total' =>0,
            'wanke_total' =>0,
            'wanzhu_total' =>0,
            'wanjia_total'=>0,
        ];
        if(empty($child)){
            switch ($parent['level']){
                case RetailUser::LEVEL_WANJIA:
                    $data['wanjia_num'] += 1;
                case RetailUser::LEVEL_WANZHU:
                    $data['wanzhu_num'] += 1;
                case RetailUser::LEVEL_WANKE:
                    $data['wanke_num'] += 1;
                case RetailUser::LEVEL_FENS:
                    $data['fens_num'] += 1;
            }
            return $data;
        }

        foreach ($child as $c){
            $child_data = $this->digui($c['id']);
            $data['fens_num']   += $child_data['fens_num'];
            $data['wanke_num']  += $child_data['wanke_num'];
            $data['wanzhu_num'] += $child_data['wanzhu_num'];
            $data['wanjia_num'] += $child_data['wanjia_num'];
            //$data['fens_total']     += $child_data['fens_total'];
            //$data['wanke_total']    += $child_data['wanke_total'];
            //$data['wanzhu_total']   += $child_data['wanzhu_total'];
            //$data['wanjia_total']   += $child_data['wanjia_total'];
        }
        var_dump("========================");
        var_dump($parent['uid']);
        var_dump($data);
        return $data;
    }

}
